﻿using System.ComponentModel.DataAnnotations.Schema;
using Core.Domain.Events;

namespace Core.Domain.Entities;

[Table("UserRoles")]
public class UserRole : AuditableEntity
{
    public Guid UserId { get; private set; }
    public Guid RoleId { get; private set; }

    // 导航属性
    public virtual Role? Role { get; private set; }
    public virtual User? User { get; private set; }

    private UserRole() { }   // EF

    private UserRole(Guid userId, Guid roleId)
    {
        UserId = userId;
        RoleId = roleId;
        QueueDomainEvent(new UserRoleCreated(userId, roleId));
    }

    public static UserRole Create(Guid userId, Guid roleId)
    {
        if (userId == Guid.Empty || roleId == Guid.Empty)
            throw new ArgumentException("用户或角色标识无效");

        return new UserRole(userId, roleId);
    }

    /// <summary>
    /// 撤销关联（逻辑删除或物理删除）
    /// </summary>
    public void Revoke()
    {
        QueueDomainEvent(new UserRoleRevoked(UserId, RoleId));
    }

    /// <summary>
    /// 值对象式相等比较（幂等）
    /// </summary>
    /// <param name="obj"></param>
    /// <returns></returns>
    public override bool Equals(object? obj) =>
        obj is UserRole ur && ur.UserId == UserId && ur.RoleId == RoleId;

    public override int GetHashCode() => HashCode.Combine(UserId, RoleId);
}
